﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MatrixGame
{
	public partial class FieldControl : UserControl
	{
		public FieldControl()
		{
			InitializeComponent();
			Field = new Field();
		}

		#region Events

		public event EventHandler<FieldClickedEventArgs> FieldClicked;

		#endregion

		private Field mField;
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public Field Field 
		{
			get
			{
				return mField;
			}
			set
			{
				if (mField != null)
				{
					mField.FieldClicked -= mField_FieldClicked;
				}
				mField = value;
				if (mField != null)
				{
					mField.FieldClicked += mField_FieldClicked;
				}
			}
		}

		void mField_FieldClicked(object sender, FieldClickedEventArgs e)
		{
			if (FieldClicked != null)
			{
				FieldClicked(sender, e);
			}
		}

		private void FieldControl_Paint(object sender, PaintEventArgs e)
		{
			e.Graphics.Clear(Color.White);
			DrawGrid(e);

			for (int row = 0; row < Field.Size; row++)
			{
				for (int column = 0; column < Field.Size; column++)
				{
					DrawCell(e, row, column);
				}
			}
		}

		private void DrawGrid(PaintEventArgs e)
		{
			Rectangle cellBounds;
			Pen pen = Pens.LightGray;

			for (int row = 0; row < Field.Size; row++)
			{
				cellBounds = GetRectForCell(row, 0);
				int y = cellBounds.Bottom;
				e.Graphics.DrawLine(pen, 0, y, this.Width, y);
			}

			for (int column = 0; column < Field.Size; column++)
			{
				cellBounds = GetRectForCell(0, column);
				int x = cellBounds.Right;
				e.Graphics.DrawLine(pen, x, 0, x, this.Height);
			}
		}

		private void DrawCell(PaintEventArgs e, int row, int column)
		{
			if (Field[row, column])
			{
				e.Graphics.FillRectangle(Brushes.Yellow, GetRectForCell(row, column));
			}
		}

		Rectangle GetRectForCell(int row, int column)
        {
			int size = Field.Size;
			int x = this.Width * column / size;
			int y = this.Height * row / size;
			return new Rectangle(
				x,
				y,
				this.Width * (column + 1) / size - 1 - x,
				this.Height * (row + 1) / size - 1 - y);
        }

		FieldCoordinates GetCellFromPoint(int x, int y)
		{
			FieldCoordinates result = new FieldCoordinates
			{
				Row = Field.Size * y / this.Height,
				Column = Field.Size * x / this.Width
			};
			Field.EnsureCoordinatesValid(result);
			return result;
		}

		private void FieldControl_MouseDown(object sender, MouseEventArgs e)
		{
			FieldCoordinates coords = GetCellFromPoint(e.X, e.Y);
			Field.CellClicked(coords.Row, coords.Column);
			this.Refresh();
		}
	}
}
